package com.example.demo.handler;

import java.io.IOException;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.demo.utils.WebSocketUtil;

@Controller
//@ServerEndpoint支持stomp协议
@ServerEndpoint("/ChatHandler/{uname}")
public class ChatHandler {
	@OnOpen//建立连接
	public void openSession(@PathParam("uname") String uname,Session session) {
		String message = "欢迎："+uname+"加入";
		//将当前用户放入群聊
		WebSocketUtil.sessionmap.put(uname, session);
		//所有人发消息
		WebSocketUtil.sendAll(message);
	}
	//接收消息时
	@OnMessage
	public void onMessage(@PathParam("uname") String uname,String message) {
		message=uname+":"+message;
		WebSocketUtil.sendAll(message);
	}
	//离开聊天室
	@OnClose
	public void onClose(@PathParam("uname") String uname,Session session) {
		WebSocketUtil.sessionmap.remove(uname);
		//群发
		WebSocketUtil.sendAll("用户:"+uname+"离开聊天室");
		//关闭session
		try {
			session.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	
	//连接出现异常
//	@OnError
//	public void onError() {
//		
//	}
}
